using Zhaoxi.Zhihu.HotService.Data;
using Zhaoxi.Zhihu.SharedKerel.Result;
using Zhaoxi.Zhihu.UseCases.Common.Queries.Interfaces;

public class QuestionStatQuery(IDaraQueryService queryService)
{
    public async Task<Result<Dictionary<int, QuestionStat>>> GetLatest()
    {
        var createdAtBegin = DateTimeOffset. Now.AddDays(-7);
        var lastModifiedBegin = DateTimeOffset. Now.AddHours(-48);
        
        var questions = queryService. Questions;
        var answers = queryService. Answers;

        var queryable = from question in questions
            join answer in answers on question.Id equals answer.QuestionId
            group answer by new
            {
                question.Id,
                question.ViewCount,
                question.FollowCount,
                question.LastModifiedAt,
                question.CreateAt
            }
            into g
            where g.Key.LastModifiedAt >= lastModifiedBegin
                  && g.Key.CreateAt >= createdAtBegin
            orderby g.Key.ViewCount descending
            select new
            {
                Id = g.Key.Id,
                ViewCount = g.Key.ViewCount,
                FollowCount = g.Key.FollowCount,
                AnswerCount = g.Count(),
                LikeCount = g.Sum(answers => answers.LikeCount)
            };
        var questionList=await queryService.ToListAsync(queryable);
        if (questionList.Count == 0) return Result.NotFound();
        
        var questionStat = questionList.ToDictionary(item=>item.Id,item=>new QuestionStat
        {
            ViewCount = item.ViewCount,
            FollowCount = item.FollowCount,
            AnswerCount = item.AnswerCount,
            LikeCount = item.LikeCount
            
        });
        return Result. Success(questionStat);

    }
}